<template>
  <el-form
    size="medium"
    class="padding-20px"
    :model="form"
    :rules="rules"
    ref="form"
  >
    <el-form-item prop="email">
      <el-input
        :placeholder="$t('register.email')"
        v-model="form.email"
      >
      </el-input>
    </el-form-item>
    <el-form-item prop="name">
      <el-input
        :placeholder="$t('register.name')"
        v-model="form.name"
      ></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        show-password
        :placeholder="$t('register.password')"
        v-model="form.password"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <button
        type="primary"
        class="w-100"
        @click="submit()"
        :disabled="registerBtnEnabled"
      >{{$t('register.signUp')}}</button>
      <router-link
        to="/"
        class="float-r"
      >{{$t('register.hasAccount')}}</router-link>
    </el-form-item>
  </el-form>
</template>
<script>
import { register, checkEmail } from '@/assets/api/index'
const BLUR = 'blur'
export default {
  data () {
    return {
      form: {},
      registerBtnEnabled: true,
      rules: {
        email: [
          { required: true, trigger: BLUR, message: this.$t('validationMessage.inputRequired') },
          { type: 'email', trigger: BLUR, message: this.$t('validationMessage.emailFormat') },
          { validator: this.validateEmail, trigger: BLUR }
        ],
        password: [
          { required: true, trigger: BLUR, message: this.$t('validationMessage.inputRequired') },
          { min: 6, max: 12, trigger: BLUR, message: this.$t('validationMessage.lengthRange', { min: 6, max: 12 }) }
        ],
        name: [
          { required: true, trigger: BLUR, message: this.$t('validationMessage.inputRequired') },
          { min: 3, max: 12, trigger: BLUR, message: this.$t('validationMessage.lengthRange', { min: 6, max: 12 }) }
        ]
      }
    }
  },
  methods: {
    submit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.account = this.form.email
          register(this.form).then(res => {
            if (res.data === 'failed') {
              this.$message({ type: 'warning', message: this.$t('register.registerFailed') })
            } else {
              this.$message({ type: 'success', message: this.$t('register.registerSuccessed') })
              this.$router.push({ path: '/' })
            }
          })
        }
      })
    },
    validateEmail (rules, value, callback) {
      checkEmail({ email: value }).then(res => {
        if (res.data) {
          this.registerBtnEnabled = false
          callback()
        } else {
          callback(new Error(this.$t('register.emailAlreadyExist')))
        }
      })
    }
  }
}
</script>
